﻿// (c) Copyright Michael Antonio.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Subsonic.Data;
using System.Windows.Threading;
using Subsonic.Resources;
using System.IO.IsolatedStorage;
using Subsonic.ViewModels;
using MichMan.Utilities;
using System.IO;
using Subsonic.Controls;
using System.Threading;
using Microsoft.Phone.Marketplace;
using Microsoft.Phone.Tasks;
using MichMan.Utilities.Requests;
using System.Diagnostics;

namespace Subsonic
{
    public partial class App : Application
    {
        static App()
        {
            PhoneCacheManager.Register();
        }

        public static new App Current
        {
            get
            {
                return Application.Current as App;
            }
        }

        // Easy access to the root frame
        public PhoneApplicationFrame RootFrame { get; private set; }

        private static Finder<MediaElement> _mediaElement = new Finder<MediaElement>();
        public static MediaElement MediaElement
        {
            get
            {
                return _mediaElement.Value();
            }
        }

        private static Finder<ProgressBar> _progressBar = new Finder<ProgressBar>();
        private static ProgressBar ProgressBar
        {
            get
            {
                return _progressBar.Value();
            }
        }

        // Constructor
        public App()
        {
            // Global handler for uncaught exceptions. 
            // Note that exceptions thrown by ApplicationBarItem.Click will not get caught here.
            UnhandledException += Application_UnhandledException;

            // Standard Silverlight initialization
            InitializeComponent();

            // Phone-specific initialization
            InitializePhoneApplication();
        }

        public void AttachRequest(IRequest request)
        {
            if (request != null && request.IsBusy)
            {
                request.RunRequestCompleted += request_RunRequestCompleted;
                ProgressBarVisibility = Visibility.Visible;
            }
        }

        void request_RunRequestProgressChanged(object sender, RunRequestProgressChangedEventArgs e)
        {
            ProgressBar.Value = (double)e.BytesReceived * 1000.0 / (double)e.TotalBytesToReceive;
        }

        void request_RunRequestCompleted(object sender, RunRequestCompletedEventArgs e)
        {
            IRequest req = (IRequest)sender;
            req.RunRequestCompleted -= request_RunRequestCompleted;
            ProgressBarVisibility = Visibility.Collapsed;
            if (req.RequestStatus == RequestStatus.Error)
            {
                MessageBox.Show(String.Format("Request failed with error: {0}", req.Error.Message));
            }
        }


        // Not sure if this is too annoying.  The help file is probably enough.
        Once trialMessageShown = new Once();
        public void ShowTrialMessage()
        {
            /*
            if (!trialMessageShown.True)
            {
                if ((new LicenseInformation()).IsTrial())
                {
                    MessageBoxResult r = MessageBox.Show("{trial_message}".StaticResource(), "{trial_title}".StaticResource(), MessageBoxButton.OKCancel);
                    if (r == MessageBoxResult.OK)
                    {
                        MarketplaceDetailTask detailTask = new MarketplaceDetailTask();
                        detailTask.Show();
                    }
                }
            }
             */
        }

        Once progressBarAvailable = new Once(() => ProgressBar != null);
        void RootFrame_LayoutUpdatedProgressBar(object sender, EventArgs e)
        {
            if (progressBarAvailable.Value)
            {
                RootFrame.LayoutUpdated -= new EventHandler(RootFrame_LayoutUpdatedProgressBar);

                // It's possible for someone to try to attach to the progress bar before it is 
                // even created.  In that case, show it as soon as possible.
                if (progressBarVisibilityCount > 0)
                {
                    ProgressBar.Visibility = Visibility.Visible;
                    ProgressBar.IsIndeterminate = true;
                }
            }
        }

        Once mediaElementAvailable = new Once(() => MediaElement != null);
        void RootFrame_LayoutUpdatedMediaElement(object sender, EventArgs e)
        {
            if (mediaElementAvailable.Value)
            {
                MediaElement.CurrentStateChanged += new RoutedEventHandler(MediaElement_CurrentStateChanged);
                MusicPlayer.Instance.Attach(MediaElement);
                RootFrame.LayoutUpdated -= new EventHandler(RootFrame_LayoutUpdatedMediaElement);
                ResumePlayback();
            }
        }

        int progressBarVisibilityCount = 0;
        public Visibility ProgressBarVisibility
        {
            get
            {
                return ProgressBar.Visibility;
            }
            set
            {
                if (value == Visibility.Visible)
                {
                    progressBarVisibilityCount++;
                }
                else
                {
                    progressBarVisibilityCount--;
                }

                // In case there's some weirdness where part of the app double hides the progress bar.
                if (progressBarVisibilityCount < 0)
                {
                    Debugger.Break();
                }
                progressBarVisibilityCount = Math.Max(progressBarVisibilityCount, 0);

                if (progressBarVisibilityCount > 1)
                {
                    Debug.WriteLine("Progress Bar:  Count = {0} Visibility = {1}.  No change.", progressBarVisibilityCount, ProgressBar.Visibility);
                    return;
                }

                if (ProgressBar != null)
                {
                    ProgressBar.Visibility = value;
                    ProgressBar.IsIndeterminate = (value == Visibility.Visible);
                    Debug.WriteLine("Progress Bar:  Count = {0} Visibility = {1}.  Change.", progressBarVisibilityCount, ProgressBar.Visibility);
                }
                else
                {
                    Debug.WriteLine("Progress Bar:  Count = {0} Visibility = {1}.  Progress bar not available.", progressBarVisibilityCount, value);
                }
            }
        }

        // bool mediaElementShowingProgress = false;
        void MediaElement_CurrentStateChanged(object sender, RoutedEventArgs e)
        {
            /*
            if (ProgressBar != null)
            {
                if (MediaElement.CurrentState == MediaElementState.Buffering && !mediaElementShowingProgress)
                {
                    mediaElementShowingProgress = true;
                    ProgressBarVisibility = Visibility.Visible;
                }
                if (MediaElement.CurrentState != MediaElementState.Buffering && mediaElementShowingProgress)
                {
                    mediaElementShowingProgress = false;
                    ProgressBarVisibility = Visibility.Collapsed;
                }
            }
             */
        }

        bool playbackResumed = false;
        void ResumePlayback()
        {
            if (!playbackResumed)
            {
                playbackResumed = true;
                IsolatedStorageSettingsCache issc = new IsolatedStorageSettingsCache();
                if (!String.IsNullOrEmpty((string)issc.Get(MusicPlayer.currentSongKey)))
                {
                    MusicPlayer.Instance.OnResume();
                }
            }
        }

        // Code to execute when the application is launching (eg, from Start)
        // This code will not execute when the application is reactivated
        private void Application_Launching(object sender, LaunchingEventArgs e)
        {
            ApplicationLaunchingOrActivated();
        }

        // Code to execute when the application is activated (brought to foreground)
        // This code will not execute when the application is first launched
        private void Application_Activated(object sender, ActivatedEventArgs e)
        {
            trialMessageShown.Set();
            ApplicationLaunchingOrActivated();
        }

        /// <summary>
        /// Common functionality for Launching and Activated events.
        /// </summary>
        private void ApplicationLaunchingOrActivated()
        {
            playbackResumed = false;
            RootFrame.LayoutUpdated += new EventHandler(RootFrame_LayoutUpdatedMediaElement);
            RootFrame.LayoutUpdated += new EventHandler(RootFrame_LayoutUpdatedProgressBar);

        }

        // Code to execute when the application is deactivated (sent to background)
        // This code will not execute when the application is closing
        private void Application_Deactivated(object sender, DeactivatedEventArgs e)
        {
        }

        // Code to execute when the application is closing (eg, user hit Back)
        // This code will not execute when the application is deactivated
        private void Application_Closing(object sender, ClosingEventArgs e)
        {
        }

        // Code to execute if a navigation fails
        void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // A navigation has failed; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        // Code to execute on Unhandled Exceptions
        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (e.ExceptionObject is SubsonicException)
            {
                string msg = "{background_task_parse_error}";
                SubsonicException se = (SubsonicException)e.ExceptionObject;
                switch(se.Code)
                {
                    case 20:
                        msg = "{parser_upgrade_client}";
                        break;
                    case 30:
                        msg = "{parser_upgrade_server}";
                        break;
                    case 40:
                        msg = "{parser_not_authenticated}";
                        break;
                    case 60:
                        msg = "{select_album_donate_dialog_0_trial_days_left}";
                        break;
                }
                MessageBox.Show(msg.StaticResource());
                return;
            }

            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
        }

        #region Phone application initialization

        // Avoid double-initialization
        private bool phoneApplicationInitialized = false;

        // Do not add any additional code to this method
        private void InitializePhoneApplication()
        {
            if (phoneApplicationInitialized)
                return;

            // Create the frame but don't set it as RootVisual yet; this allows the splash
            // screen to remain active until the application is ready to render.
            RootFrame = new PhoneApplicationFrame();
            RootFrame.Template = App.Current.Resources["MediaFrameTemplate"] as ControlTemplate;
            RootFrame.Navigated += CompleteInitializePhoneApplication;

            // Handle navigation failures
            RootFrame.NavigationFailed += RootFrame_NavigationFailed;

            // Ensure we don't initialize again
            phoneApplicationInitialized = true;
        }

        // Do not add any additional code to this method
        private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
        {
            // Set the root visual to allow the application to render
            if (RootVisual != RootFrame)
                RootVisual = RootFrame;

            // Remove this handler since it is no longer needed
            RootFrame.Navigated -= CompleteInitializePhoneApplication;
        }

        #endregion
    }
}
